package com.california.pay.service;

import com.california.pay.config.CommonErrors;
import com.california.pay.consts.NotifyStatus;
import com.california.pay.consts.OrderStatus;
import com.california.pay.exception.BusinessException;
import com.california.pay.persist.domain.MchPayQuota;
import com.california.pay.persist.domain.PayOrder;
import com.california.pay.persist.mapper.MchPayQuotaMapper;
import com.california.pay.persist.mapper.PayOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 */
@Slf4j
@Service
public class OrderSupplyService {

    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private PayNotifyService payNotifyService;
    @Autowired
    private MchPayQuotaMapper payQuotaMapper;

    @Transactional(rollbackFor = {Exception.class})
    public String supplyPayOrder(String payOrderId) {
        PayOrder payOrder = payOrderMapper.selectByPrimaryKey(payOrderId);
        if (payOrder == null) {
            throw new BusinessException(CommonErrors.UNDEFINED, "不存在该订单");
        }

        PayOrder updatePayOrder = new PayOrder();
        updatePayOrder.setOrderId(payOrderId);
        updatePayOrder.setUpdateTime(new Date());
        // 重新设置通知状态
        updatePayOrder.setMchNotifyStatus(NotifyStatus.NONE);
        updatePayOrder.setMchNotifyCount(0);
        updatePayOrder.setLastMchNotifyTime(0L);
        updatePayOrder.setTxnAmount(payOrder.getTotalAmount());

        if (!payOrder.getOrderStatus().equals(OrderStatus.PAY_SUCC)) {
            updatePayOrder.setOrderStatus(OrderStatus.PAY_SUCC);

            MchPayQuota record = payQuotaMapper.selectOneByMchIdAndPayDate(payOrder.getPayDate(), payOrder.getChannelMchId());
            payQuotaMapper.addPayAmountByPrimaryKey(updatePayOrder.getTxnAmount(), record.getQuotaId());
        }

        payOrderMapper.updateByPrimaryKeySelective(updatePayOrder);

        payOrder = payOrderMapper.selectByPrimaryKey(payOrderId);
        payNotifyService.notifyOrderToMch(payOrder);
        return payOrderId;
    }
}
